package com.example.ccmusic

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


private const val TAG = "MainActivity"

class MainActivity : AppCompatActivity() {
    private var recyclerView: RecyclerView? = null
    private var currentMusicView: View? = null
    private var adapter: MusicAdapter? = null
    private var icon: ImageView? = null
    private var name: TextView? = null
    private var author: TextView? = null
    private lateinit var viewModel: MusicViewModel


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                1
            )
        } else {
            refreshMusic()
        }

        viewModel = ViewModelProvider(this)[MusicViewModel::class.java]

        viewModel.currentMusic().observe(this) { onCurrentChanged(it) }

        recyclerView = findViewById(R.id.music_list)

        val listener = object : MusicAdapter.ItemClickListener {
            override fun onClick(position: Int, item: Music) {
                Log.d(TAG, "onClick: position = $position, item = $item")
                val intent = Intent(this@MainActivity, MusicService::class.java)
                intent.putExtra(Constants.EXTRA_COMMAND, Constants.COMMAND_CHANGE_MUSIC)
                intent.putExtra(Constants.EXTRA_MUSIC, item)
                this@MainActivity.startForegroundService(intent)
                if (viewModel.currentMusic().value == item) {
                    toDetail()
                } else {
                    viewModel.changeCurrentMusic(item)
                }
            }
        }
        adapter = MusicAdapter(this, listener)
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.VERTICAL
        recyclerView?.let {
            it.adapter = adapter
            it.layoutManager = layoutManager
        }

        currentMusicView = findViewById(R.id.footer_music)
        currentMusicView?.setOnClickListener {
            toDetail()
        }

        icon = findViewById(R.id.music_icon)
        name = findViewById(R.id.music_name)
        author = findViewById(R.id.music_author)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "你没有权限", Toast.LENGTH_SHORT).show()
            } else {
                refreshMusic()
            }
        }
    }

    private fun refreshMusic() {
        lifecycleScope.launch(Dispatchers.Main) {
            val list = withContext(Dispatchers.IO) {
                Log.d(TAG, "onCreate: Dispatchers thread: ${Thread.currentThread()}")
                viewModel.queryMusic(contentResolver)
            }
            adapter?.submitList(list)
        }
    }

    private fun onCurrentChanged(music: Music) {
        Log.d(TAG, "onCreate: current changed")
        lifecycleScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                ImageUtils.getBitmapByAlbumId(this@MainActivity, music.albumId)
            }?.let { icon?.setImageBitmap(it) }
        }
        name?.text = music.title
        author?.text = music.artist
    }

    private fun toDetail() {
        Log.d(TAG, "toDetail")
    }
}